<template>
  <el-drawer v-model="dialogVisible" title="推送用户" direction="rtl" size="60%">
    <ContentWrap>
      <!-- 搜索工作栏 -->
      <CommonQueryFormBar v-model="queryParams" @query="handleQuery" @reset="resetQuery">
        <template #default>
          <el-form-item label="昵称" prop="nickname">
            <el-input
              v-model="queryParams.nickname"
              class="!w-240px"
              clearable
              placeholder="请输入用户昵称"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="手机号" prop="mobile">
            <el-input
              v-model="queryParams.mobile"
              class="!w-240px"
              clearable
              placeholder="请输入手机号"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="会员等级" prop="userLevel">
            <el-select
              v-model="queryParams.userLevel"
              placeholder="请选择会员等级"
              clearable
              class="!w-240px"
            >
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.MEMBER_LEVEL)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </template>

        <template #more>
          <el-form-item label="性别" prop="sex">
            <el-select
              v-model="queryParams.sex"
              placeholder="请选择性别"
              clearable
              class="!w-240px"
            >
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.SYSTEM_USER_SEX)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="年龄" prop="age">
            <el-input
              v-model="queryParams.age"
              class="!w-240px"
              clearable
              placeholder="请输入年龄"
              @keyup.enter="handleQuery"
            />
          </el-form-item>

          <el-form-item label="婚况" prop="marriage">
            <el-select
              v-model="queryParams.marriage"
              placeholder="请选择婚况"
              clearable
              class="!w-240px"
            >
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.MARITAL_STATUS)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="有孩子" prop="withChild">
            <el-select
              v-model="queryParams.marriage"
              placeholder="请选择婚况"
              clearable
              class="!w-240px"
            >
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.HAVE_CHILDREN)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="想要孩子" prop="wantChild">
            <el-select
              v-model="queryParams.marriage"
              placeholder="请选择婚况"
              clearable
              class="!w-240px"
            >
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.WANT_CHILD)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            /></el-select>
          </el-form-item>
          <el-form-item label="是否购车" prop="car">
            <el-select
              v-model="queryParams.marriage"
              placeholder="请选择婚况"
              clearable
              class="!w-240px"
            >
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.PURCHASE_CAR)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="是否购房" prop="house">
            <el-select
              v-model="queryParams.marriage"
              placeholder="请选择婚况"
              clearable
              class="!w-240px"
            >
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.PURCHASE_SITUATION)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="学历" prop="educationAttainment">
            <el-select
              v-model="queryParams.marriage"
              placeholder="请选择婚况"
              clearable
              class="!w-240px"
            >
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.USER_EDUCATION)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            /></el-select>
          </el-form-item>
          <el-form-item label="是否吸烟" prop="smoking">
            <el-select
              v-model="queryParams.marriage"
              placeholder="请选择婚况"
              clearable
              class="!w-240px"
            >
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.HAVA_SMOK)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="是否喝酒" prop="drink">
            <el-select
              v-model="queryParams.marriage"
              placeholder="请选择婚况"
              clearable
              class="!w-240px"
            >
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.HAVE_DRINK)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="结婚时间" prop="timeOfMarriage">
            <el-date-picker
              v-model="queryParams.timeOfMarriage"
              class="!w-240px"
              type="date"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
        </template>
      </CommonQueryFormBar>
    </ContentWrap>

    <!-- 列表 -->
    <ContentWrap>
      <el-table v-loading="loading" :data="list" :show-overflow-tooltip="true" :stripe="true">
        <!-- <el-table-column align="center" label="会员编号" prop="userNo" /> -->
        <el-table-column align="center" label="会员ID" prop="id" />
        <el-table-column align="center" label="昵称" prop="nickname" />
        <el-table-column align="center" label="手机号" prop="mobile" width="120px" />
        <!-- <el-table-column align="center" label="姓名" prop="name" /> -->
        <el-table-column
          align="center"
          label="性别"
          prop="sex"
          :formatter="sexFormatter"
          width="80px"
        >
          <template #default="scope">
            <dict-tag :type="DICT_TYPE.SYSTEM_USER_SEX" :value="scope.row.sex || ''" />
          </template>
        </el-table-column>
        <el-table-column align="center" label="年龄" prop="age" width="80px" />
        <el-table-column align="center" label="婚况" prop="marriage" width="100px">
          <template #default="scope">
            <dict-tag :type="DICT_TYPE.MARITAL_STATUS" :value="scope.row.marriage || ''" />
          </template>
        </el-table-column>
        <el-table-column align="center" label="会员等级" prop="userLevel" width="100px">
          <template #default="scope">
            <dict-tag :type="DICT_TYPE.MEMBER_LEVEL" :value="scope.row.userLevel || ''" />
          </template>
        </el-table-column>
        <el-table-column
          :formatter="dateFormatter"
          align="center"
          label="到期时间"
          prop="memberEndTime"
          width="180px"
        />
        <el-table-column
          :show-overflow-tooltip="false"
          align="center"
          fixed="right"
          label="操作"
          width="200px"
        >
          <template #default="scope">
            <div class="flex items-center justify-center">
              <el-button link type="primary" @click="openDetail(scope.row.id)">详情</el-button>
              <el-button
                link
                type="danger"
                @click="handlePush(scope.row)"
                v-hasPermi="['system:user:delete']"
              >
                推送
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <Pagination
        v-model:limit="queryParams.pageSize"
        v-model:page="queryParams.pageNo"
        :total="total"
        @pagination="getList"
      />
    </ContentWrap>
  </el-drawer>

  <!-- 推送用户详情弹窗：查看 -->
  <UserDetail ref="formRefDetail" />
</template>

<script lang="ts" setup>
import { onMounted } from 'vue'
import {
  TUITranslateService,
  TUIStore,
  StoreName,
  IConversationModel,
  SendMessageParams,
  TUIChatService
} from '@tencentcloud/chat-uikit-engine'
import { isEnabledMessageReadReceiptGlobal } from '../../utils/utils'
import { sexFormatter } from '@/utils/formatter'
import { dateFormatter } from '@/utils/formatTime'
import * as UserApi from '@/api/member/user'
import { DICT_TYPE, getIntDictOptions, getStrDictOptions } from '@/utils/dict'
import * as MemMessageApi from '@/api/blind/memMessage/index.ts'
import UserDetail from '@/views/blind/member/Detail.vue'
import { TUIChatEngine } from '@/TUIKit'

defineOptions({ name: 'MemberUser' })

const dialogVisible = ref(false) // 弹窗的是否展示

const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref([]) // 列表的数据
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  nickname: null,
  mobile: null,
  loginDate: [],
  createTime: [],
  tagIds: [],
  levelId: null,
  userLevel: undefined,
  groupId: null,
  sex: null,
  age: null,
  hunKuang: null,
  chindren: null,
  car: null,
  house: null,
  educationAttainment: null,
  smoking: null,
  drink: null,
  timeOfMarriage: null,
  marriage: null,
  withChild: null,
  wantChild: null
})
const selectedIds = ref<number[]>([]) // 表格的选中 ID 数组

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await UserApi.getUserPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  handleQuery()
}

// TIM 相关
const currentConversation = ref<IConversationModel>()

TUIStore.watch(StoreName.CONV, {
  currentConversation: (conversation: IConversationModel) => {
    currentConversation.value = conversation
  }
})

// 推送
const handlePush = (user: any) => {
  console.log(user)

  const options = {
    to:
      currentConversation?.value?.groupProfile?.groupID ||
      currentConversation?.value?.userProfile?.userID,
    conversationType: currentConversation?.value?.type,
    payload: {
      data: JSON.stringify({
        // 推荐用户消息标识字段 id
        businessID: `user`,
        // 消息内容
        userId: user.id,
        avatar: user.avatar,
        nickname: user.nickname,
        sex: user.sex,
        innerMonologue: user.innerMonologue
      }),
      description: '',
      extension: ''
    },
    needReadReceipt: isEnabledMessageReadReceiptGlobal()
  } as SendMessageParams

  // 发送消息
  TUIChatService.sendCustomMessage(options)

  // 提交后关闭 dialog
  dialogVisible.value = false

  // DC：记录聊天信息
  const CustomconversationID = ref()
  TUIStore.watch(StoreName.CUSTOM, {
    CustomconversationID: (id: string) => {
      CustomconversationID.value = id
    }
  })
  const IMUserId = TUIChatEngine.userID
  const queryParams = {
    conversationID: `C2C${options.to}`,
    recordId: CustomconversationID.value,
    sendMemId: IMUserId,
    reciveMemId: options.to,
    messageType: 'TIMCustomElem',
    // messageType: currentConversation?.value?.lastMessage?.type,
    messageContent: options.payload.data
  }

  MemMessageApi.MemMessageCreate(queryParams)
}

/** 打开详情 */
const formRefDetail = ref()
const openDetail = (id?: number) => {
  formRefDetail.value.open(id)
}

/** 打开弹窗 */
const open = async (id: number) => {
  dialogVisible.value = true
}
defineExpose({ open }) // 提供 open 方法，用于打开弹

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>
